
using System;
using System.Collections.Generic;
using System.Net.Json;
using Dokan;
using System.IO;

namespace CouchFS
{


	public class DirectoryHelper
	{
        /// <summary>
        /// http://172.16.106.128:5984/couchfs/_view/tree/getdirectory?key=%22\/root%22
        /// </summary>
        /// <param name="host"></param>
        /// <param name="Path"></param>
        /// <returns></returns>
        public static List<FileInformation> GetDirectory(string host, string Path)
        {
            List<FileInformation> ret = new List<FileInformation>();

            Path = Path.Replace("\\", "/");

            if (Path == "/")
                Path = "";
            String content;
            if (RESTHelper.RequestGet(host, Path, out content))
            {
                JsonTextParser parser = new JsonTextParser();
                JsonObject json = parser.Parse(content);
                JsonObject rows = null;
                foreach (JsonObject field in json as JsonObjectCollection)
                {
                    string name = field.Name;
                    if (name == "rows")
                    {
                        rows = field;
                        break;
                    }
                }

                foreach (JsonObject files in rows as JsonArrayCollection)
                {
                    ret.Add(AddFile(files));
                }
            }

            return ret;
        }

        private static FileInformation AddFile(JsonObject json)
        {
            FileInformation fi = new FileInformation();
            fi.Attributes = new System.IO.FileAttributes();
//            FileAttributes.Directory();
            fi.CreationTime = DateTime.Now;
            fi.LastAccessTime = DateTime.Now;
            fi.LastWriteTime = DateTime.Now;
            fi.Length = 0;

            foreach (JsonObject field in json as JsonObjectCollection)
            {
                string key = field.Name;

                if (key == "isdirectory")
                {
                    fi.Attributes = FileAttributes.Directory;
                }

                if (key == "isfile")
                {
                    fi.Attributes = FileAttributes.Normal;
                }

                if (key == "value")
                {
                    string value = (string)field.GetValue();
                    fi.FileName = value;
                }
            }
            return fi;
        }
	}
}
